#!/usr/bin/env python3
"""
测试后端连接的脚本
"""

import requests
import json
import time

def test_connection():
    """测试后端连接"""
    base_url = "http://127.0.0.1:8000"
    
    print("🔍 测试后端服务连接...")
    print(f"📍 服务地址: {base_url}")
    
    # 测试基本连接
    test_endpoints = [
        ("/", "根路径"),
        ("/health/", "健康检查"),
        ("/docs", "API文档"),
        ("/api/v1/tts/voices", "TTS语音列表"),
    ]
    
    for endpoint, description in test_endpoints:
        try:
            print(f"\n📡 测试 {description} ({endpoint})")
            
            url = base_url + endpoint
            response = requests.get(url, timeout=10)
            
            print(f"   ✅ 状态码: {response.status_code}")
            
            if response.status_code == 200:
                try:
                    data = response.json()
                    if isinstance(data, dict):
                        print(f"   📄 响应类型: JSON")
                        if 'status' in data:
                            print(f"   📊 状态: {data['status']}")
                        elif len(data) < 100:
                            print(f"   📋 内容: {json.dumps(data, ensure_ascii=False, indent=2)}")
                        else:
                            print(f"   📋 内容长度: {len(str(data))} 字符")
                    else:
                        print(f"   📄 响应类型: {type(data)}")
                        print(f"   📋 内容: {str(data)[:100]}...")
                except json.JSONDecodeError:
                    print(f"   📄 响应类型: HTML/文本")
                    print(f"   📋 内容长度: {len(response.text)} 字符")
            else:
                print(f"   ❌ 错误信息: {response.text}")
                
        except requests.exceptions.Timeout:
            print(f"   ⏰ 超时: 请求超过10秒")
        except requests.exceptions.ConnectionError:
            print(f"   🔌 连接错误: 无法连接到服务")
        except Exception as e:
            print(f"   ❌ 其他错误: {e}")
    
    print(f"\n🎯 完整的API文档地址: {base_url}/docs")
    print(f"🏥 健康检查地址: {base_url}/health/")
    
    return True

if __name__ == "__main__":
    test_connection()
